import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_provider_demo/commons/log.dart';
import 'package:flutter_provider_demo/config/di.dart';
import 'package:flutter_provider_demo/config/environment.dart';
import 'package:flutter_provider_demo/config/router.dart';
import 'package:flutter_provider_demo/config/theme.dart';
import 'package:flutter_provider_demo/data/repositories/schedule_repository.dart';
import 'package:flutter_provider_demo/data/repositories/settings_repository.dart';
import 'package:flutter_provider_demo/data/services/database_helper.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import 'package:flutter_gen/gen_l10n/app_localizations.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  Env.init();

  final database = await DatabaseHelper().database;

  FlutterError.onError = (details) {
    Log().fatal("Flutter error1", details.exception, details.stack);
  };

  // Run the app
  runApp(
    MultiProvider(
      providers: providers(database),
      child: const MainApp(),
    ),
  );
}

class MainApp extends StatefulWidget {
  const MainApp({super.key});

  @override
  State<MainApp> createState() => _MainAppState();
}

class _MainAppState extends State<MainApp> {
  // Use StatefulWidget to avoid rebuild router when trigger a hot load
  // In production mode, you'd better to change it to StatelessWidget.
  late final GoRouter _goRouter;
  @override
  void initState() {
    super.initState();
    _goRouter = router(context.read());
  }

  @override
  Widget build(BuildContext context) {
    ScheduelRepository scheduelRepository = context.read<ScheduelRepository>();
    scheduelRepository.start();

    SettingsRepository settingsRepository = context.read<SettingsRepository>();

    return FutureBuilder(
      future: settingsRepository.initialize(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return MaterialApp(
            home: const Scaffold(
              body: Center(
                child: CircularProgressIndicator(),
              ),
            ),
          );
        }

        // Extract the route out of the _AppContent
        // To prevent it rebuild after change ThemeMode or Language
        // This code snippet is moved to the initState function when use StatefulWidget
        // final goRoute = router(context.read());

        return Consumer<SettingsRepository>(builder: (context, settings, __) {
          return _AppContent(
            settingsRepository: settings,
            router: _goRouter,
          );
        });
      },
    );
  }
}

class _AppContent extends StatelessWidget {
  const _AppContent({required this.settingsRepository, required this.router});
  final SettingsRepository settingsRepository;
  final GoRouter router;

  @override
  Widget build(BuildContext context) {
    // final language = context.select<SettingsRepository, String>(
    //   (value) => value.settingsModel.language,
    // );
    // final themeMode = context.select<SettingsRepository, ThemeMode>(
    //   (value) => value.settingsModel.themeMode,
    // );
    return MaterialApp.router(
      // title: 'Provider Demo',
      debugShowCheckedModeBanner: false,
      onGenerateTitle: (context) => AppLocalizations.of(context)!.appTitle,
      localizationsDelegates: [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: AppLocalizations.supportedLocales,
      locale: Locale(settingsRepository.settingsModel.language),
      theme: AppTheme.lightTheme,
      darkTheme: AppTheme.darkTheme,
      themeMode: settingsRepository.settingsModel.themeMode,
      routerConfig: router,
    );
  }
}
